package handlers;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;


public class FileHandler {

	
	public static File[] getDir(){
		File folder = new File("Shared");
		return folder.listFiles();	
	}
	
	public static ArrayList<File> getFiles(String filter){
		File[] allFiles = getDir();
		ArrayList<File> result = new ArrayList<File>();
		for(File f: allFiles){
			if(f.getName().toLowerCase().contains(filter)){
				result.add(f);
			}
		}
		return result;
	}
	
	public static String getMime(String fname){
		String ext = fname.substring(fname.lastIndexOf('.'));
		if(ext.equals(".txt") || ext.equals(".java")){
			return "text/plain";
		}
		else if(ext.equals(".xml")){
			return "application/xml";
		}
		else if(ext.equals(".avi")){
			return "video/avi";
		}
		else if(ext.equals(".pdf")){
			return "application/pdf";
		}
		else if(ext.equals(".mp3")){
			return "audio/mpeg3";
		}
		else if(ext.equals(".jpg") || ext.equals(".jpeg") || ext.equals(".jpe")){
			return "image/jpeg";
		}
		else if(ext.equals(".gif")){
			return "image/gif";
		}
		else if(ext.equals(".png")){
			return "image/png";
		}
		else{
			return "application/octet-stream";
		}
		
	}
	
	public static byte[] getRawData(String fname){
		File[] f = getDir();
		FileInputStream fis = null;
		byte[] bFile = null;
		for (File file:f){
			if (fname.equals(file.getName())){
				bFile = new byte[(int) file.length()];
				try{
					fis = new FileInputStream(file);
					fis.read(bFile);
					fis.close();
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
			}
		}
		return bFile;
	}
}
